package com.jch.ft.util;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// 对象序列化、反序列化工具 | 二进制支持 protobuf
public class SerializationUtil {

    // 缓存 模式Schema
    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();

    // 对象实例化工具 突破默认构造方法限制
    private static Objenesis objenesis = new ObjenesisStd();

    private static <T> Schema<T> getSchema(Class<T> cls){
        Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
        if (schema == null){
            schema = RuntimeSchema.createFrom(cls);
            cachedSchema.put(cls,schema);
        }
        return schema;
    }

    public static <T> byte[] serialize(T obj){
        Class<T> cls = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema<T> schema = getSchema(cls);
            return ProtostuffIOUtil.toByteArray(obj,schema,buffer);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(),e);
        } finally {
            buffer.clear();
        }
    }

    public static <T> T deserialize(byte[] data,Class<T> cls){
        try{
            T msg = objenesis.newInstance(cls);
            Schema<T> schema = getSchema(cls);
            ProtostuffIOUtil.mergeFrom(data,msg,schema);
            return msg;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(),e);
        }
    }
}
